<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\PropertyRequest;
use App\Models\Property;
use App\Services\Admin\AttributeService;
use App\Services\Admin\MetroService;
use App\Services\Admin\PropertyService;
use App\Services\Admin\RegionService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PropertyController extends Controller
{
    protected $service;
    protected $attrService;
    protected $regionService;
    protected $metroService;

    public function __construct(PropertyService $service, AttributeService $attributeService, RegionService $regionService,MetroService $metroService)
    {
        $this->service = $service;
        $this->attrService = $attributeService;
        $this->regionService = $regionService;
        $this->metroService = $metroService;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //分类
//        $categorys = Category::with('allChilds')->where('parent_id',0)->orderBy('sort','desc')->get();
        return view('admin.property.index');
    }

    public function data(Request $request)
    {
        $model = Property::query();

        if ($request->get('title')){
            $model = $model->where('title','like','%'.$request->get('title').'%');
        }
        $res = $model->orderBy('created_at','desc')->paginate($request->get('limit',30))->toArray();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //分类
//        $categorys = Category::with('allChilds')->where('parent_id',0)->orderBy('sort','desc')->get();
        // 区域
        $area = $this->regionService->getArea();
//        $other = $this->attrService->getNewHouseAttr();
        $price = $this->attrService->getAttributeById(6);
        $apartment = $this->attrService->getAttributeById(18);
        $feature = $this->attrService->getAttributeById(34);
        $wytype = $this->attrService->getAttributeById(42);
        //装修情况
        $renovation = $this->attrService->getAttributeById(47);
        return view('admin.property.create',compact('area','price','apartment','feature','wytype','renovation'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(PropertyRequest $request)
    {
        $data = $request->all();
        //格式化区域 省
//        $province = explode(',',$data['province']);
//        $data['province'] = $province[0];
//        $data['provincename'] = $province[1];
//        // 市
//        $region = explode(',',$data['region']);
//        $data['region'] = $region[0];
//        $data['regionname'] = $region[1];
//        // 区
//        if ($data['area']) {
//            $area = explode(',',$data['area']);
//            $data['area'] = $area[0];
//            $data['areaname'] = $area[1];
//        }
//        // 镇
//        if ($data['town']) {
//            $town = explode(',',$data['town']);
//            $data['town_id'] = $town[0];
//            $data['town'] = $town[1];
//        }

        $data['opentime'] = strtotime($data['opentime']);
        $data['handtime'] = strtotime($data['handtime']);
        $apartment = isset($data['apartment'])?$this->service->formatInput($data['apartment']):'';
        $feature = isset($data['feature'])?$this->service->formatInput($data['feature']):'';

        $data['apartment'] = isset($data['apartment'])?implode(',',$apartment['id']):'';
        $data['feature'] = isset($data['feature'])?implode(',',$feature['id']):'';
        $data['featuretxt'] = isset($data['feature'])?json_encode($feature['txt']):'';
        // 格式化推荐位
        $data['recommend'] = isset($data['recommend'])?implode(',',$feature['recommend']):'';
        // 经纬度
        if(!empty($data['map'])){
            $map = explode(',',$data['map']);
            $data['longitude'] = $map[0]??'';
            $data['latitude'] = $map[1]??'';
        }

        if ($data['renovation']){
            $reno = explode(',',$data['renovation']);
            $data['renovation_id'] = $reno[0];
            $data['renovation'] = $reno[1];
        }
        // 物业类型
        if ($data['wytype']){
            $wy = explode(',',$data['wytype']);
            $data['wytype'] = $wy[0];
            $data['wyname'] = $wy[1];
        }
        // 序列化多图
        if(isset($data['images']) && count($data['images'])){
            $data['images'] = serialize($data['images']);
        }
        $res = Property::create($data);
        if($res){
            $this->service->updateAttributeMid($apartment['id'],$res['id'],'property');
            $this->service->updateAttributeMid($feature['id'],$res['id'],'property');
        }
        return redirect(route('admin.property'))->with(['status'=>'添加成功']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $article = Property::findOrFail($id);
        $article->opentime = date('Y-m-d',$article->opentime);
        $article->handtime = date('Y-m-d',$article->handtime);
        $article->price = explode(',',$article->price);
        $article->apartment = explode(',',$article->apartment);
        $article->feature = explode(',',$article->feature);

        if (!$article){
            return redirect(route('admin.property'))->withErrors(['status'=>'楼盘不存在']);
        }
        // 区域
        $area = $this->regionService->getArea();
//        $other = $this->attrService->getNewHouseAttr();
        $price = $this->attrService->getAttributeById(6);
        $apartment = $this->attrService->getAttributeById(18);
        $feature = $this->attrService->getAttributeById(34);
        $wytype = $this->attrService->getAttributeById(42);
        //装修情况
        $renovation = $this->attrService->getAttributeById(47);
        // 地铁
//        $metro = $this->metroService->getMetroByCityId($article->region);
        return view('admin.property.edit',compact('article','area','price','apartment','feature','wytype','renovation'));

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(PropertyRequest $request, $id)
    {
        $article = Property::findOrFail($id);
        $data = $request->all();
        //格式化区域 省
        $province = explode(',',$data['province']);
        $data['province'] = $province[0];
        $data['provincename'] = $province[1];
        // 市
        $region = explode(',',$data['region']);
        $data['region'] = $region[0];
        $data['regionname'] = $region[1];
        // 区
        if ($data['area']) {
            $area = explode(',',$data['area']);
            $data['area'] = $area[0];
            $data['areaname'] = $area[1];
        }
        // 镇
        if ($data['town']) {
            $town = explode(',',$data['town']);
            $data['town_id'] = $town[0];
            $data['town'] = $town[1];
        }

        $data['opentime'] = strtotime($data['opentime']);
        $data['handtime'] = strtotime($data['handtime']);
        $apartment = $this->service->formatInput($data['apartment']);
        $feature = $this->service->formatInput($data['feature']);

        $data['apartment'] = isset($data['apartment'])?implode(',',$apartment['id']):'';
        $data['feature'] = isset($data['feature'])?implode(',',$feature['id']):'';
        $data['featuretxt'] = isset($data['feature'])?json_encode($feature['txt']):'';
        // 格式化推荐位
        $data['recommend'] = isset($data['recommend'])?implode(',',$data['recommend']):'';
        // 经纬度
        if(!empty($data['map'])){
            $map = explode(',',$data['map']);
            $data['longitude'] = $map[0]??'';
            $data['latitude'] = $map[1]??'';
        }
        // 装修情况
        if ($data['renovation']){
            $reno = explode(',',$data['renovation']);
            $data['renovation_id'] = $reno[0];
            $data['renovation'] = $reno[1];
        }
        // 物业类型
        if ($data['wytype']){
            $wy = explode(',',$data['wytype']);
            $data['wytype'] = $wy[0];
            $data['wyname'] = $wy[1];
        }
        // 序列化多图
        if(isset($data['images']) && count($data['images'])){
            $data['images'] = serialize($data['images']);
        }
        // 删除对应属性
        $this->service->deleteAttributeMid($id,'property');
        if($article->update($data)){
            $this->service->updateAttributeMid($apartment['id'],$id,'property');
            $this->service->updateAttributeMid($feature['id'],$id,'property');
            return redirect(route('admin.property'))->with(['status'=>'更新成功']);
        }
        return redirect(route('admin.property'))->withErrors(['status'=>'系统错误']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)){
            return response()->json(['code'=>1,'msg'=>'请选择删除项']);
        }
        foreach (Property::whereIn('id',$ids)->get() as $model){
            //删除楼盘
            $model->delete();
        }
        return response()->json(['code'=>0,'msg'=>'删除成功']);
    }

    public function getLocalPosition($city)
    {
        return view('admin.property.position',compact('city'));
    }

}
